package com.example.foodisimportant.PersonalInformationActivity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.example.foodisimportant.Body.ResponseBody;
import com.example.foodisimportant.Body.userBody;
import com.example.foodisimportant.Network.NetworkSettings;
import com.example.foodisimportant.Network.PersonNetworkThread;
import com.example.foodisimportant.R;
import com.example.foodisimportant.StudentViewActivity.Fragment.SettingsFragment;
import com.example.foodisimportant.StudentViewActivity.StudentViewActivity;
import com.example.foodisimportant.utils.BitmapUtils;
import com.example.foodisimportant.utils.CameraUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.android.material.imageview.ShapeableImageView;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.FutureTask;

public class PersonalInformationActivity extends AppCompatActivity {
    private Button mBtnExit;
    private EditText mEtname;
    private Spinner mSpcampus,mSpcollage,mSpbudget;
    private TextView mTvnumber;
    private ImageButton mIbback,mIbSave;
    private RadioGroup mRgflavour;
    private RadioButton mRbflavour;
    private final ObjectMapper mapper = new ObjectMapper();
    private String n,p,name,campus,college,budget,flavour,strimage;
    private ShapeableImageView mIvHead;
    private String rsp;
    private Object mobject;
    private SharedPreferences preferences;
    //Base64
    private String base64Pic;
    //拍照和相册获取图片的Bitmap
    private Bitmap orc_bitmap;
    //底部弹窗
    private BottomSheetDialog bottomSheetDialog;
    //弹窗视图
    private View bottomView;
    //权限请求
    private RxPermissions rxPermissions;
    private Context mcontext;
    //是否拥有权限
    private boolean hasPermissions = false;
    //存储拍完照后的图片
    private File outputImagePath;
    //启动相机标识
    public static final int TAKE_PHOTO = 1;
    //启动相册标识
    public static final int SELECT_PHOTO = 2;
    //Glide请求图片选项配置
    private RequestOptions requestOptions = RequestOptions.circleCropTransform()
            .diskCacheStrategy(DiskCacheStrategy.NONE)//不做磁盘缓存
            .skipMemoryCache(true);//不做内存缓存

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personal_information);
        init();
        preferences=mcontext.getSharedPreferences("userInfo",MODE_PRIVATE);
        //拉取
        new Thread(new Runnable() {
            @Override
            public void run() {
                Looper.prepare();
                rsp="1";
                //提取值
                FutureTask<String> PersongetTask = new FutureTask<>(new PersonNetworkThread(name,n,p,campus,college,budget,flavour,strimage,NetworkSettings.GET_INFO,rsp));
                Thread thread =new Thread(PersongetTask);
                thread.start();
                try{
                    ResponseBody body = mapper.readValue(PersongetTask.get(), ResponseBody.class);
                    /*userBody  userBody=(userBody) body.getData();
                    String userId=userBody.getUserId();
                    String userName=userBody.getUserName();
                    String userStrImage=userBody.getUserStrImage();
                    String userCampus=userBody.getUserCampus();
                    String userBudget=userBody.getUserBudget();
                    mEtname.setText(userName);
                    mTvnumber.setText(userId);
                    mIvHead.setImageBitmap(BitmapUtils.base64ToBitmap(userStrImage));
                    setSpinnerItemSelectedByValue(mSpcampus,userCampus);
                    setSpinnerItemSelectedByValue(mSpbudget,userBudget);

                     */
                    Toast.makeText(getApplicationContext(),body.getMsg()+"刷新成功",Toast.LENGTH_SHORT).show();
                }catch (Exception e){
                    e.printStackTrace();
                }
                Looper.loop();
            }
        }).start();
        
        //退出登录
        mBtnExit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //创建意图对象
                Intent intent1 = new Intent(PersonalInformationActivity.this, StudentViewActivity.class);
                //设置传递键值对
                intent1.putExtra("data",1);
                //激活意图
                finish();
                startActivity(intent1);
                /*
                Intent intent= new Intent(PersonalInformationActivity.this, LoginTest.class);
                finish();
                startActivity(intent);
                 */
            }
        });

        //返回
        mIbback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        //保存
        mIbSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Looper.prepare();
                        rsp="0";
                        //对应值
                        name=mEtname.getText().toString();
                        campus=mSpcampus.getSelectedItem().toString();
                        college=mSpcollage.getSelectedItem().toString();
                        budget=mSpbudget.getSelectedItem().toString();
                        flavour=mRbflavour.getText().toString();
                        strimage=putImageToShare(mIvHead);
                        //提取值
                        FutureTask<String> PersonpostTask = new FutureTask<>(new PersonNetworkThread(name,n,p,campus,college,budget,flavour,strimage,NetworkSettings.POST_INFO,rsp));
                        Thread thread =new Thread(PersonpostTask);
                        thread.start();
                        try{
                            ResponseBody body = mapper.readValue(PersonpostTask.get(), ResponseBody.class);
                            if(body.getCode() == 1){
                                Toast.makeText(getApplicationContext(),body.getMsg()+"修改成功",Toast.LENGTH_SHORT).show();
                                Intent intent = new Intent(PersonalInformationActivity.this, SettingsFragment.class);
                                finish();
                                startActivity(intent);
                            }else {
                                Toast.makeText(getApplicationContext(),"修改失败",Toast.LENGTH_SHORT).show();
                            }
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                        Looper.loop();
                    }
                }).start();
            }
        });
    }

    //选完照片返回
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            //拍照后返回
            case TAKE_PHOTO:
                if (resultCode == RESULT_OK) {
                    //显示图片
                    displayImage(outputImagePath.getAbsolutePath());
                }
                break;
            //打开相册后返回
            case SELECT_PHOTO:
                if (resultCode == RESULT_OK) {
                    String imagePath = null;
                    //判断手机系统版本号
                    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
                        //4.4及以上系统使用这个方法处理图片
                        imagePath = CameraUtils.getImageOnKitKatPath(data, this);
                    } else {
                        imagePath = CameraUtils.getImageBeforeKitKatPath(data, this);
                    }
                    //显示图片
                    displayImage(imagePath);
                }
                break;
            default:
                break;
        }
    }

    //Toast提示
    private void showMsg(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    //检查版本
    private void checkVersion() {
        //Android6.0及以上版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //如果你是在Fragment中，则把this换成getActivity()
            rxPermissions = new RxPermissions(this);
            //权限请求
            rxPermissions.request(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    .subscribe(granted -> {
                        if (granted) {//申请成功
                            showMsg("已获取权限");
                            hasPermissions=true;
                        } else {//申请失败
                            showMsg("权限未开启");
                            hasPermissions=false;
                        }
                    });
        } else {
            //Android6.0以下
            showMsg("无需请求动态权限");
        }
    }

    //更换头像
    public void changeAvatar(View view) {
        bottomSheetDialog = new BottomSheetDialog(this);
        bottomView = getLayoutInflater().inflate(R.layout.dialog_bottom, null);
        bottomSheetDialog.setContentView(bottomView);
        bottomSheetDialog.getWindow().findViewById(R.id.design_bottom_sheet).setBackgroundColor(Color.TRANSPARENT);
        TextView tvTakePictures = bottomView.findViewById(R.id.tv_take_pictures);
        TextView tvOpenAlbum = bottomView.findViewById(R.id.tv_open_album);
        TextView tvCancel = bottomView.findViewById(R.id.tv_cancel);

        //拍照
        tvTakePictures.setOnClickListener(v -> {
            takePhoto();
            showMsg("拍照");
            bottomSheetDialog.cancel();
        });
        //打开相册
        tvOpenAlbum.setOnClickListener(v -> {
            openAlbum();
            showMsg("打开相册");
            bottomSheetDialog.cancel();
        });
        //取消
        tvCancel.setOnClickListener(v -> {
            bottomSheetDialog.cancel();
        });
        bottomSheetDialog.show();
    }

    //拍照
    private void takePhoto() {
        if (!hasPermissions) {
            showMsg("未获取到权限");
            checkVersion();
            return;
        }
        SimpleDateFormat timeStampFormat = new SimpleDateFormat(
                "yyyy_MM_dd_HH_mm_ss");
        String filename = timeStampFormat.format(new Date());
        outputImagePath = new File(getExternalCacheDir(),
                filename + ".jpg");
        Intent takePhotoIntent = CameraUtils.getTakePhotoIntent(this, outputImagePath);
        // 开启一个带有返回值的Activity，请求码为TAKE_PHOTO
        startActivityForResult(takePhotoIntent, TAKE_PHOTO);
    }

    //打开相册
    private void openAlbum() {
        if (!hasPermissions) {
            showMsg("未获取到权限");
            checkVersion();
            return;
        }
        startActivityForResult(CameraUtils.getSelectPhotoIntent(), SELECT_PHOTO);
    }

    //通过图片路径显示图片
    private void displayImage(String imagePath) {
        if (!TextUtils.isEmpty(imagePath)) {
            //显示图片
            Glide.with(this).load(imagePath).apply(requestOptions).into(mIvHead);
            //压缩图片
            orc_bitmap = CameraUtils.compression(BitmapFactory.decodeFile(imagePath));
            //转Base64
            base64Pic = BitmapUtils.bitmapToBase64(orc_bitmap);

        } else {
            showMsg("图片获取失败");
        }
    }

    //图片转化为字节流，进一步转化为string
    public static String putImageToShare(ImageView imageView) {
        BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
        Bitmap bitmap = drawable.getBitmap();
        ByteArrayOutputStream byStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 80, byStream);
        byte[] byteArray = byStream.toByteArray();
        String imgString = new String(Base64.encodeToString(byteArray, Base64.DEFAULT));
        return imgString;
    }

   //初始化
    private void init(){
        mBtnExit=findViewById(R.id.exit_logined);
        mEtname=findViewById(R.id.wode_nicheng);
        mSpcampus=findViewById(R.id.xiaoqu_sp);
        mSpcollage=findViewById(R.id.xueyuan_sp);
        mSpbudget=findViewById(R.id.yusuan_sp);
        mIvHead=findViewById(R.id.wode_touxiang);
        mIbSave=findViewById(R.id.savemyinformation);
        mIbback=findViewById(R.id.back);
        mRgflavour=findViewById(R.id.rg);
        mRbflavour=findViewById(R.id.rb1);
        mTvnumber=findViewById(R.id.numbersetting);
        mRgflavour.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                mRbflavour=findViewById(group.getCheckedRadioButtonId());
            }
        });
    }

    //设置spinner
    public void setSpinnerItemSelectedByValue(Spinner spinner, String value){
        SpinnerAdapter adapter=spinner.getAdapter();
        for(int i=0;i<adapter.getCount();i++){
            if(value!=null&!"".equals(value.trim())&value.equals(adapter.getItem(i).toString())){
                spinner.setSelection(i,true);
                break;
            }
        }
    }

}
